// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('nonghua', ['ionic', 'nonghua.controllers.sales', 'nonghua.controllers.distributor', 'usense.chat', 'nonghua.controllers.system', 'nonghua.controllers.node', 'nonghua.services', 'nonghua.directives','ngMessages', 'door3.css', 'jrCrop','nonghua.controllers.farmer', 'nonghua.controllers.village'])

    .run(function ($ionicPlatform, $rootScope, $state, $ionicHistory, $timeout) {
        $ionicPlatform.ready(function () {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                cordova.plugins.Keyboard.disableScroll(true);

            }
            // this will override
            // see http://devgirl.org/2014/07/31/phonegap-developers-guid/
            //if (window.StatusBar) {
            //    // org.apache.cordova.statusbar required
            //    StatusBar.styleDefault();
            //}
            //ionic.Platform.showStatusBar(false);
            //ionic.Platform.fullScreen(false,true);

            $rootScope.oldlimit = 0;
            $rootScope.newlimit = 999999999;
            $rootScope.picture_default = "http://www.metercomm.com.cn/nonghua/sites/default/files/default_images/default_user.png";

            $rootScope.goBack = function() {
                $ionicHistory.goBack();
            };

            $rootScope.chatConfig = {
                appName : 'nonghua',
                devWidth : ((window.innerWidth > 0) ? window.innerWidth : screen.width),
                serverAddr : "wss://www.junong360.com:9999"
            };

            $rootScope.isEmployee = function (roles) {
                return !empty(roles) && (!empty(roles[6]) || !empty(roles[4]) || !empty(roles[5]) || !empty(roles[9]) || !empty(roles[3]));
            };
            $rootScope.isFarmer = function (roles) {
                return !empty(roles) && (!empty(roles[8]));
            };
            $rootScope.isSales = function (roles) {
                return !empty(roles) && (!empty(roles[3]) || !empty(roles[4]) || !empty(roles[5]));
            };
            $rootScope.isDistributor = function (roles) {
                return !empty(roles) && (!empty(roles[7]) || !empty(roles[3]));
            };
            $rootScope.canUpgrade = function (roles) {
                if (!empty(roles) && !empty(roles[2])) {
                    for (var role in roles) {
                        if (role != 2) {
                            return false;
                        }
                    }
                    return true;
                } else {
                    return false;
                }
            };

            $rootScope.user_access = function (string) {
                try {
                    //if (_user_has_role("administrator", $rootScope.user)) {
                    //    return true;
                    //}
                    var access = false;
                    for (var index in $rootScope.user.permissions) {
                        if (!$rootScope.user.permissions.hasOwnProperty(index)) {
                            continue;
                        }
                        var object = $rootScope.user.permissions[index];
                        if (object.permission == string) {
                            access = true;
                            break;
                        }
                    }
                    return access;
                }
                catch (error) {
                    console.log('user_access - ' + error);
                }
            };

            userInit($rootScope, navigator.splashscreen, $state, $timeout);
        });
    })

    .config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

        $ionicConfigProvider.tabs.position("bottom");
        $ionicConfigProvider.views.transition("none");
        //if (ionic.Platform.isAndroid()) {
            $ionicConfigProvider.scrolling.jsScrolling(false);
        //}

        $ionicConfigProvider.navBar.alignTitle('center');

        // Ionic uses AngularUI Router which uses the concept of states
        // Learn more here: https://github.com/angular-ui/ui-router
        // Set up the various states which the app can be in.
        // Each state's controller can be found in controllers.js
        $stateProvider
            .state('intro', {
                url: '/intro',
                templateUrl: 'templates/system-templates/intro.html',
                controller: 'IntroCtrl'
            })
            .state('register', {
                url: '/register',
                templateUrl: 'templates/system-templates/register.html',
                controller: 'RegisterCtrl'
            })
            // route to show our basic form (/forgot-password)
            .state('forgot-password', {
                url: '/forgot-password',
                templateUrl: 'templates/system-templates/forgot-password.html',
                controller: 'ForgotPassCtrl'
            })
            // nested states
            .state('forgot-password.checkDigit', {
                url: '/checkDigit',
                templateUrl: 'templates/system-templates/checkDigit.html'
            })
            .state('forgot-password.modifyPass', {
                url: '/modifyPass',
                templateUrl: 'templates/system-templates/changePass.html'
            })
            .state('account-upgrade-farmer', {
                url: '/account_upgrade_farmer',
                templateUrl: 'templates/system-templates/account-upgrade-farmer.html',
                controller: 'AccountUpgradeFarmerCtrl'
            })
            // route to show our basic form (/modify-password)
            .state('modify-password', {
                url: '/modify-password',
                templateUrl: 'templates/system-templates/modify-password.html',
                controller: 'ModifyPassCtrl'
            })
            // nested states
            .state('modify-password.checkDigit', {
                url: '/checkDigit',
                templateUrl: 'templates/system-templates/checkDigit.html'
            })
            .state('modify-password.modifyPass', {
                url: '/modifyPass',
                templateUrl: 'templates/system-templates/changePass.html'
            })
            .state('genuine-verification', {
                url: "/genuine_verification",
                templateUrl: "templates/farmer-templates/genuine-verification.html",
                controller: 'GenuineVerificationCtrl'
            })
            .state('tabs', {
                url: '/tabs',
                abstract: true,
                templateUrl: 'templates/system-templates/tabs.html'
            })
            .state('tabs.main', {
                url: '/main',
                views: {
                    'home-tab': {
                        templateUrl: 'templates/system-templates/main.html',
                        controller: 'MainCtrl'
                        //css: 'css/main.css'
                    }
                }
            })
            .state('tabs.article-list', {
                url: '/articles/:articleType',
                views: {
                    'article-tab': {
                        templateUrl: 'templates/node-templates/article-list.html',
                        controller: 'ArticleListCtrl'
                    }
                }
            })
            .state('tabs.case-list', {
                url: '/case',
                views: {
                    'article-tab': {
                        templateUrl: 'templates/node-templates/article-list.html',
                        controller: 'CaseListCtrl'
                    }
                }
            })
            .state('tabs.news-list', {
                url: '/news',
                views: {
                    'article-tab': {
                        templateUrl: 'templates/node-templates/article-list.html',
                        controller: 'NewsListCtrl'
                    }
                }
            })
            .state('tabs.market-list', {
                url: '/market',
                views: {
                    'article-tab': {
                        templateUrl: 'templates/node-templates/article-list.html',
                        controller: 'MarketListCtrl'
                    }
                }
            })
            .state('tabs.knowledge-list', {
                url: '/knowledge',
                views: {
                    'article-tab': {
                        templateUrl: 'templates/node-templates/article-list.html',
                        controller: 'KnowledgeListCtrl'
                    }
                }
            })
            .state('article-detail', {
                url: '/article/:lid/:nid',
                templateUrl: 'templates/node-templates/article-detail.html',
                controller: 'ArticleDetailCtrl'
            })
            .state('tabs.my-account', {
                url: "/my-account",
                views: {
                    'account-tab': {
                        templateUrl: "templates/system-templates/my-account.html",
                        controller: 'MyAccountCtrl'
                    }
                }
            })
            .state('tabs.change-picture', {
                url: "/change-picture",
                views: {
                    'account-tab': {
                        templateUrl: "templates/system-templates/change-picture.html",
                        controller: 'ChangePictureCtrl'
                    }
                }
            })
            .state('tabs.consult-list', {
                url: '/consult/:viewMode',
                views: {
                    'home-tab': {
                        templateUrl: 'templates/node-templates/consult-list.html',
                        controller: 'ConsultListCtrl'
                    }
                }
            })
            .state('tabs.consult-add', {
                url: '/consult/add',
                views: {
                    'home-tab': {
                        templateUrl: 'templates/node-templates/consult-add.html',
                        controller: 'ConsultAddCtrl'
                    }
                }
            })
            .state('tabs.consult-detail', {
                url: '/consult/:lid/:nid',
                views: {
                    'home-tab': {
                        templateUrl: 'templates/node-templates/consult-detail.html',
                        controller: 'ConsultDetailCtrl'
                    }
                }
            })
            .state('chat', {
                url: '/chat/:chatId/:chatName',
                templateUrl: 'templates/chat-templates/chat-detail.html',
                controller: 'ChatDetailCtrl'
                //views: {
                //    'chat-tab': {
                //        templateUrl: 'templates/chat-templates/chat-detail.html',
                //        controller: 'ChatDetailCtrl'
                //    }
                //}
            })
            .state('error', {
                url: '/error',
                templateUrl: 'templates/system-templates/error.html',
                controller: 'ErrorCtrl'
            })
            .state('capacity-list', {
                url: '/capacity/list',
                templateUrl: 'templates/sales-templates/capacity-list.html',
                controller: 'CapacityListCtrl'
            })
            .state('capacity-stats', {
                url: '/capacity/stats',
                templateUrl: 'templates/sales-templates/capacity-stats.html',
                controller: 'CapacityStatsCtrl'
            })
            .state('plant-structure-stats', {
                url: '/plant_structure/stats',
                templateUrl: 'templates/sales-templates/plant-structure-stats.html',
                controller: 'PlantStructureStatsCtrl'
            })
            .state('competitors-stats', {
                url: '/competitors/stats',
                templateUrl: 'templates/sales-templates/competitors-stats.html',
                controller: 'CompetitorsStatsCtrl'
            })
            .state('brand-sales-stats', {
                url: '/brand_sales/stats',
                templateUrl: 'templates/sales-templates/brand-sales-stats.html',
                controller: 'BrandSalesStatsCtrl'
            })
            .state('stock-info-stats', {
                url: '/stock_info/stats',
                templateUrl: 'templates/distributor-templates/stock-info-stats.html',
                controller: 'StockInfoStatsCtrl'
            })
            .state('monthly-report-stats', {
                url: '/monthly_report/stats',
                templateUrl: 'templates/distributor-templates/monthly-report-stats.html',
                controller: 'MonthlyReportStatsCtrl'
            })
            .state('invoice-stats', {
                url: '/invoice/stats',
                templateUrl: 'templates/distributor-templates/invoice-stats.html',
                controller: 'InvoiceStatsCtrl'
            })
            .state('competitors-list', {
                url: '/competitors/list',
                templateUrl: 'templates/sales-templates/competitors-list.html',
                controller: 'CompetitorsListCtrl'
            })
            .state('competitors-detail', {
                url: '/competitors/:id',
                templateUrl: 'templates/sales-templates/competitors-detail.html',
                controller: 'CompetitorsDetailCtrl'
            })
            //.state('competitors-stats', {
            //    url: '/competitors/stats',
            //    templateUrl: 'templates/sales-templates/competitors-stats.html',
            //    controller: 'CompetitorsStatsCtrl'
            //})
            .state('brand-sales-list', {
                url: '/brand_sales/list',
                templateUrl: 'templates/sales-templates/brand-sales-list.html',
                controller: 'BrandSalesListCtrl'
            })
            .state('plant-structure-list', {
                url: '/plant_structure/list',
                templateUrl: 'templates/sales-templates/plant-structure-list.html',
                controller: 'PlantStructureListCtrl'
            })
            .state('sales-log-list', {
                url: '/sales_log/list',
                templateUrl: 'templates/sales-templates/sales-log-list.html',
                controller: 'SalesLogListCtrl'
            })
            .state('monthly-report-list', {
                url: '/monthly_report/list',
                templateUrl: 'templates/distributor-templates/monthly-report-list.html',
                controller: 'MonthlyReportListCtrl'
            })
            .state('monthly-report-detail', {
                url: '/monthly_report/:id',
                templateUrl: 'templates/distributor-templates/monthly-report-detail.html',
                controller: 'MonthlyReportDetailCtrl'
            })
            .state('invoice-list', {
                url: '/invoice/list',
                templateUrl: 'templates/distributor-templates/invoice-list.html',
                controller: 'InvoiceListCtrl'
            })
            .state('invoice-detail', {
                url: '/invoice/:id',
                templateUrl: 'templates/distributor-templates/invoice-detail.html',
                controller: 'InvoiceDetailCtrl'
            })
            .state('village-activity-list', {
                url: '/village_activity/list',
                templateUrl: 'templates/village-templates/village-activity-list.html',
                controller: 'VillageActivityListCtrl'
            })
            .state('village-activity-detail', {
                url: '/village_activity/:id',
                templateUrl: 'templates/village-templates/village-activity-detail.html',
                controller: 'VillageActivityDetailCtrl'
            })
            .state('experts-work-list', {
                url: '/experts_work/list',
                templateUrl: 'templates/village-templates/experts-work-list.html',
                controller: 'ExpertsWorkListCtrl'
            })
            .state('experts-work-detail', {
                url: '/experts_work/:id',
                templateUrl: 'templates/village-templates/experts-work-detail.html',
                controller: 'ExpertsWorkDetailCtrl'
            })
            .state('farmer-list', {
                url: '/farmer/list',
                templateUrl: 'templates/farmer-templates/farmer-list.html',
                controller: 'FarmerListCtrl'
            })
            .state('farmer-detail', {
                url: '/farmer/:id',
                templateUrl: 'templates/farmer-templates/farmer-detail.html',
                controller: 'FarmerDetailCtrl'
            })
            .state('revisit-list', {
                url: '/revisit/list',
                templateUrl: 'templates/farmer-templates/revisit-list.html',
                controller: 'RevisitListCtrl'
            })
            .state('revisit-detail', {
                url: '/revisit/:id',
                templateUrl: 'templates/farmer-templates/revisit-detail.html',
                controller: 'RevisitDetailCtrl'
            })
            .state('fertilizer-case-list', {
                url: '/fertilizer_case/list',
                templateUrl: 'templates/farmer-templates/fertilizer-case-list.html',
                controller: 'FertilizerCaseListCtrl'
            })
            .state('fertilizer-case-detail', {
                url: '/fertilizer_case/:id',
                templateUrl: 'templates/farmer-templates/fertilizer-case-detail.html',
                controller: 'FertilizerCaseDetailCtrl'
            })
            .state('plant-info-list', {
                url: '/plant_info/list',
                templateUrl: 'templates/farmer-templates/plant-info-list.html',
                controller: 'PlantInfoListCtrl'
            })
            .state('plant-info-detail', {
                url: '/plant_info/:id',
                templateUrl: 'templates/farmer-templates/plant-info-detail.html',
                controller: 'PlantInfoDetailCtrl'
            })
            .state('soil-info-list', {
                url: '/soil_info/list',
                templateUrl: 'templates/farmer-templates/soil-info-list.html',
                controller: 'SoilInfoListCtrl'
            })
            .state('soil-info-detail', {
                url: '/soil_info/:id',
                templateUrl: 'templates/farmer-templates/soil-info-detail.html',
                controller: 'SoilInfoDetailCtrl'
            })
            .state('stock-info-list', {
                url: '/stock_info/list',
                templateUrl: 'templates/distributor-templates/stock-info-list.html',
                controller: 'StockInfoListCtrl'
            })
            .state('stock-info-detail', {
                url: '/stock_info/:id',
                templateUrl: 'templates/distributor-templates/stock-info-detail.html',
                controller: 'StockInfoDetailCtrl'
            })
            .state('capacity-detail', {
                url: '/capacity/:id',
                templateUrl: 'templates/sales-templates/capacity-detail.html',
                controller: 'CapacityDetailCtrl'
            })
            .state('brand-sales-detail', {
                url: '/brand_sales/:id',
                templateUrl: 'templates/sales-templates/brand-sales-detail.html',
                controller: 'BrandSalesDetailCtrl'
            })
            .state('plant-structure-detail', {
                url: '/plant_structure/:id',
                templateUrl: 'templates/sales-templates/plant-structure-detail.html',
                controller: 'PlantStructureDetailCtrl'
            })
            .state('retailstore-list', {
                url: '/retailstore/list',
                templateUrl: 'templates/sales-templates/retailstore-list.html',
                controller: 'RetailstoreListCtrl'
            })
            .state('retailstore-detail', {
                url: '/retailstore/:id',
                templateUrl: 'templates/sales-templates/retailstore-detail.html',
                controller: 'RetailstoreDetailCtrl'
            })
            .state('sales-log-detail', {
                url: '/sales_log/:id',
                templateUrl: 'templates/sales-templates/sales-log-detail.html',
                controller: 'SalesLogDetailCtrl'
            });

        // if none of the above states are matched, use this as the fallback
        //$urlRouterProvider.otherwise('/tabs/main');
        // Set the site path (without the trailing slash).
        //Drupal.settings.site_path = "http://127.0.0.1/nonghua"; // http://www.example.com
        Drupal.settings.site_path = "https://www.junong360.com"; // http://www.example.com
        //Drupal.settings.site_path = "http://www.metercomm.com.cn/nonghua"; // http://www.example.com
        // Set the Service Resource endpoint path.
        Drupal.settings.endpoint = "drupalgap";
        Drupal.settings.debug = true;

    })

    .filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }])

    .filter('orderObjectBy', function () {
        return function (items, field_1, field_2, reverse) {
            var filtered = [];
            angular.forEach(items, function (item) {
                filtered.push(item);
            });
            filtered.sort(function (a, b) {
                return (a[field_1] > b[field_1] ? 1 : ((a[field_1] == b[field_1] && a[field_2] > b[field_2]) ? 1 : -1));
            });
            if (reverse) {
                filtered.reverse();
            }
            return filtered;
        };
    })
    .filter('orderObjectById', function () {
        return function (items, id, reverse) {
            var filtered = [];
            angular.forEach(items, function (item) {
                filtered.push(item);
            });
            filtered.sort(function (a, b) {
                return (parseInt(a[id]) - parseInt(b[id]));
            });
            if (reverse) {
                filtered.reverse();
            }
            return filtered;
        };
    });
